package com.stylefeng.guns.modular.yjya.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.stylefeng.guns.common.persistence.dao.RoadnetMapper;
import com.stylefeng.guns.common.persistence.model.PassengerNum;
import com.stylefeng.guns.common.persistence.model.Roadnet;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.yjya.service.IPassengerNumService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客流管理控制器
 *
 * @author wsk
 * @Date 2018-07-10 10:52:21
 */
@Controller
@RequestMapping("/passengerNum")
public class PassengerNumController extends BaseController {

    private String PREFIX = "/yjya/passengerNum/";

    @Autowired
    private IPassengerNumService passengerNumService;

    @Autowired
    private RoadnetMapper roadnetMapper;

    /**
     * 跳转到客流管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "passengerNum.html";
    }

    /**
     * 跳转到添加客流管理
     */
    @RequestMapping("/passengerNum_add")
    public String passengerNumAdd() {
        return PREFIX + "passengerNum_add.html";
    }

    /**
     * 跳转到修改客流管理
     */
    @RequestMapping("/passengerNum_update/{passengerNumId}")
    public String passengerNumUpdate(@PathVariable Integer passengerNumId, Model model) {
        PassengerNum passengerNum = passengerNumService.selectById(passengerNumId);
        model.addAttribute("item",passengerNum);
        LogObjectHolder.me().set(passengerNum);
        return PREFIX + "passengerNum_edit.html";
    }

    /**
     * 获取客流管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return passengerNumService.selectList(null);
    }

    /**
     * 新增客流管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(PassengerNum passengerNum) {
        passengerNumService.insert(passengerNum);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除客流管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer passengerNumId) {
        passengerNumService.deleteById(passengerNumId);
        return SUCCESS_TIP;
    }

    /**
     * 修改客流管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(PassengerNum passengerNum) {
        passengerNumService.updateById(passengerNum);
        return super.SUCCESS_TIP;
    }

    /**
     * 客流管理详情
     */
    @RequestMapping(value = "/detail/{passengerNumId}")
    @ResponseBody
    public Object detail(@PathVariable("passengerNumId") Integer passengerNumId) {
        return passengerNumService.selectById(passengerNumId);
    }


    /**
     导出Excel模板
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "客流");
        modelMap.put(NormalExcelConstants.CLASS, PassengerNum.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("客流列表", "导出人:" + ShiroKit.getUser().getName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }

    /**
     * 客流上传
     * @param multipartHttpServletRequest
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST,path = "/importExcel")
    @ResponseBody
    public String importExcel(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse response,HttpServletRequest request)throws Exception{
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        for(Map.Entry<String,MultipartFile> entity : fileMap.entrySet()){
            MultipartFile multipartFile = entity.getValue(); //获取上传文件对象
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(2);
            importParams.setHeadRows(1);
            importParams.setNeedSave(true);
            List <PassengerNum> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(),PassengerNum.class,importParams);
            List<Roadnet> roadnetList = roadnetMapper.selectList(null);
            for(int i = 0;i<list.size();i++){
                list.get(i).setDateStatus(3);
                for(int j=0;j<roadnetList.size();j++){

                    if(list.get(i).getStartLineName().equals(roadnetList.get(j).getName())){
                        list.get(i).setStartLine(roadnetList.get(j).getId());
                    }
                    if(list.get(i).getEndLineName().equals(roadnetList.get(j).getName())){
                        list.get(i).setEndLine(roadnetList.get(j).getId());
                    }
                    if(list.get(i).getStartStationName().equals(roadnetList.get(j).getName())&&roadnetList.get(j).getPid()==list.get(i).getStartLine()){
                        list.get(i).setStartStation(roadnetList.get(j).getId());
                    }
                    if(list.get(i).getEndStationName().equals(roadnetList.get(j).getName())&&roadnetList.get(j).getPid()==list.get(i).getEndLine()){
                        list.get(i).setEndStation(roadnetList.get(j).getId());
                    }
                }
            }
            passengerNumService.insertBatch(list);
            if (!multipartFile.isEmpty()) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss");
                    String fileName = multipartFile.getOriginalFilename();
                    String filenewName = format.format(new Date()) + "_" + Math.round(Math.random() * 100000) + fileName.substring(fileName.lastIndexOf("."));
                    // 文件保存路径
                    String filePath = "E://passenger//" + filenewName;
                    // 转存文件
                    multipartFile.transferTo(new File(filePath));
                    multipartFile.getInputStream().close();
                    return filenewName;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            multipartFile.getInputStream().close();
        }
        return "文件导入成功";
    }



}
